package zero.tech.games.gateway.config;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.http.server.RequestPath;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;

import com.alibaba.fastjson.JSONObject;

import reactor.core.publisher.Mono;
import zero.tech.core.data.JwtUtil;
import zero.tech.core.data.Resp;
import zero.tech.core.data.SimpleUser;
import zero.tech.games.common.Code;
import zero.tech.games.common.RedisConsts;
@Component
public class HttpTokenFilter implements GlobalFilter{
	@Autowired
	private GatewayFilterProperties gatewayFilterProperties;
	@Override
	public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
		RequestPath path=exchange.getRequest().getPath();
//		URI url=exchange.getAttribute(ServerWebExchangeUtils.GATEWAY_REQUEST_URL_ATTR);
//		String serviceId = exchange.getAttribute(GatewayConsts.GATEWAY_SERVICE_ID);
		if(gatewayFilterProperties.getNoTokenInterceptions().contains(path.toString())) {
			//不需要进行拦截token
			return chain.filter(exchange);
		}else {
			//需要进行拦截token
			String token=exchange.getRequest().getHeaders().getFirst("token");
			if(StringUtils.isBlank(token)) {
				return MonoUtil.getVoidMono(exchange,Resp.build(Code.TOKEN_UNAVAILABLE, "token失效,重新登陆"));
			}
			SimpleUser simpleUser = JwtUtil.parseJWT(token);
			if(simpleUser==null) {
				return MonoUtil.getVoidMono(exchange,Resp.build(Code.TOKEN_UNAVAILABLE, "token失效,重新登陆"));
			}
			//登陆过的用户
			ServerHttpRequest.Builder mutate=exchange.getRequest().mutate();
			String simpleUserStr=JSONObject.toJSONString(simpleUser);
			try {
				mutate.header(RedisConsts.GATEWAY_USER,URLEncoder.encode(simpleUserStr,"UTF-8"));
			} catch (UnsupportedEncodingException e) {
				e.printStackTrace();
			}
			return chain.filter(exchange);
		}
	}


}
